package com.example.administrator.yanfoxconn.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.activity.TimeDatePickerDialog;
import com.example.administrator.yanfoxconn.bean.CanYinInfo;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.bean.ZhiyinshuiCheckMsg;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyGridView;
import com.example.administrator.yanfoxconn.widget.TouchImageView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static androidx.core.app.ActivityCompat.startActivityForResult;

/**
 * Created by Song on 2021/9/4
 * description：照片上傳點檢共用
 */
public class CanYinSecondAdapter extends RecyclerView.Adapter<CanYinSecondAdapter.ViewHolder> {
    private List<CanYinInfo> lists;
    private static HashMap<Integer, ArrayList<String>> imagePathsMap=new HashMap<>(); //存放圖片地址的map
    private static HashMap<Integer, GridAdapter> gridMap = new HashMap<>(); //存放GridAdapter的map
    private static HashMap<Integer, ArrayList<String>> showPhoto = new HashMap();//存放展示圖片
    private static HashMap<Integer, String> etLists = new HashMap<>();//用户人數存储条目的
    private  HashMap<Integer, String> conLists = new HashMap<>();//用户人數存储条目的
    public static Context mContext;
    private static int pos;
    public boolean isChange;
    private static final int REQUEST_CAMERA_CODE = 11;
    private static final int REQUEST_PREVIEW_CODE = 22;
    ImageView hivEmpty;
    GridView hgvPhoto;
    private String flag,isPhoto;
    private int photoNum;

    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView tvItem,tvContent;//序號 部位 檢查項目
        EditText etPeopleNum;//人數
        LinearLayout llAbnormal,llSigle;//異常信息
        ImageView ivEmpty;//空白图片占位
        MyGridView gvPhoto;//图片显示区域
        GridLayout glShowPhoto;//已有圖片顯示

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvItem = (TextView) itemView.findViewById(R.id.tv_item);
            tvContent = itemView.findViewById(R.id.tv_content);
            etPeopleNum = itemView.findViewById(R.id.et_input);
            llAbnormal = itemView.findViewById(R.id.ll_abnormal);
            ivEmpty = itemView.findViewById(R.id.iv_empty);
            gvPhoto = itemView.findViewById(R.id.gv_photo);
            glShowPhoto = itemView.findViewById(R.id.gl_get_image);
        }
    }

    public CanYinSecondAdapter(Context context, List<CanYinInfo> lists, String flag, HashMap<Integer, ArrayList<String>> photo, String isPhoto,HashMap<Integer, String> content){
        this.lists=lists;
        this.mContext = context;
        this.flag = flag;
        this.showPhoto=photo;
        this.isPhoto =isPhoto;
        this.conLists = content;
    }
    public CanYinSecondAdapter(Context context, List<CanYinInfo> lists,String flag,String isPhoto){
        this.lists=lists;
        this.mContext = context;
        this.flag = flag;
        this.isPhoto =isPhoto;
    }

    /**
     * 重写 避免滑动过程界面混乱
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        return position;
    }
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int position) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.adapter_canyin_second,parent,false);
        ViewHolder holder = new ViewHolder(view);
        int num=position+1;
        holder.tvItem.setText(""+num);
        photoNum=Integer.parseInt(lists.get(position).getContent());
        holder.ivEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                hivEmpty = holder.ivEmpty;
                hgvPhoto = holder.gvPhoto;
                setPosition(position);
                Log.e("-----------","imageViewposition=="+position);
                PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(photoNum); // 最多选择照片数量，默认为3
                intent.setSelectedPaths(imagePathsMap.get(position)); // 已选中的照片地址， 用于回显选中状态
                startActivityForResult((Activity) mContext,intent, REQUEST_CAMERA_CODE,null);
            }
        });

        int cols = mContext.getResources().getDisplayMetrics().widthPixels / mContext.getResources().getDisplayMetrics().densityDpi;
        cols = cols < 4 ? 4 : cols;
        holder.gvPhoto.setNumColumns(cols);

        holder.gvPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
                int position = holder.getAdapterPosition();
                setPosition(position);
                hivEmpty = holder.ivEmpty;
                hgvPhoto = holder.gvPhoto;
                Log.e("-----------","gridViewposition=="+position);
                if (pos == imagePathsMap.get(position).size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(photoNum); // 最多选择照片数量，默认为3
                    intent.setSelectedPaths(imagePathsMap.get(position)); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult((Activity) mContext,intent, REQUEST_CAMERA_CODE,null);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(mContext);
                    intent.setCurrentItem(pos);
                    intent.setPhotoPaths(imagePathsMap.get(position));
                    startActivityForResult((Activity) mContext,intent, REQUEST_PREVIEW_CODE,null);
                }
            }
        });

        holder.etPeopleNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                int position = holder.getAdapterPosition();
                etLists.put(position,holder.etPeopleNum.getText().toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        int num=position+1;
        CanYinInfo canYinInfo = lists.get(position);
        holder.tvItem.setText(num+"");
        holder.tvContent.setText(canYinInfo.getName());
        if (flag.equals("SJ1")||flag.equals("SJ2")||flag.equals("SJ3")||flag.equals("SJ4")){
            holder.etPeopleNum.setText(conLists.get(position));
            holder.etPeopleNum.setVisibility(View.VISIBLE);
        }else{
            holder.etPeopleNum.setVisibility(View.GONE);
        }

//           if (imagePathsMap.get(position)!=null){
//               imagePathsMap.get(position).clear();
//               gridMap.put(position,null);
//               loadAdpater(imagePathsMap.get(position),position);
//           }


        holder.glShowPhoto.removeAllViews();
        if (isPhoto.equals("Y")) {
            holder.glShowPhoto.setVisibility(View.VISIBLE);

//            Log.e("------imgStr0-----", "======" + showPhoto.get(position).get(0));
            if (showPhoto.get(position).size()!=0){
                for (int i = 0; i < showPhoto.get(position).size(); i++) {

                    Log.e("------imgStr-----", "======" + showPhoto.get(position).get(i));
                    TouchImageView imageView = new TouchImageView(mContext);
//                        ImageView imageView = new ImageView(ZhiyinshuiExceDetailActivity.this);
                    String imgStr = showPhoto.get(position).get(i);
                    Log.e("------imgStr-----", "======" + imgStr);
                    byte[] decode = Base64.decode(imgStr, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
                    imageView.setAdjustViewBounds(true);
                    imageView.setScaleType(ImageView.ScaleType.CENTER);
                    imageView.setImageBitmap(bitmap);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, 200);
                    layoutParams.setMargins(10, 10, 10, 10);
                    imageView.setLayoutParams(layoutParams);
                    int finalI = i;
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                    onClickListener.onclick(position, finalI, view);
                        }
                    });
                    holder.glShowPhoto.addView(imageView);
                }}
        }else{
            holder.glShowPhoto.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return lists.size();
    }

    public static int getPosition() {
        return pos;
    }

    public static void setPosition(int position) {
        CanYinSecondAdapter.pos = position;
    }

    public static HashMap<Integer, ArrayList<String>> getImagePathsMap() {
        return imagePathsMap;
    }

    public static void setImagePathsMap(HashMap<Integer, ArrayList<String>> imagePathsMap) {
        CanYinSecondAdapter.imagePathsMap = imagePathsMap;
    }

    public static HashMap<Integer, String> getEtLists() {
        return etLists;
    }

    public static void setEtLists(HashMap<Integer, String> etLists) {
        CanYinSecondAdapter.etLists = etLists;
    }

    public void loadAdpater(ArrayList<String> paths, int position) {

        imagePathsMap.put(position,paths);

        Log.e("-----Position----","Position=="+position);
        if (imagePathsMap.get(position).size() > 0) {
            hivEmpty.setVisibility(View.GONE);
        } else {
            hivEmpty.setVisibility(View.VISIBLE);
        }
        gridMap.put(position,new CanYinSecondAdapter.GridAdapter(imagePathsMap.get(position)));
        hgvPhoto.setAdapter(gridMap.get(position));
    }
    public void setAdpater(ArrayList<String> paths, int position) {

        imagePathsMap.put(position,paths);

        Log.e("-----Position----","Position=="+position);
        if (imagePathsMap.get(position).size() > 0) {
            hivEmpty.setVisibility(View.GONE);
        } else {
            hivEmpty.setVisibility(View.VISIBLE);
        }
        gridMap.put(position,new CanYinSecondAdapter.GridAdapter(imagePathsMap.get(position)));
        hgvPhoto.setAdapter(gridMap.get(position));
    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == photoNum) {
                return photoNum;
            } else {
                return listUrls.size() + 1;
            }
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
//                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_image, null);

                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }
            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == photoNum) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(mContext)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }
    private OnClickListener onClickListener;
    public void setOnClickListener(OnClickListener paramOnClickListener)
    {
        this.onClickListener = paramOnClickListener;
    }

    public  interface OnClickListener
    {
        void onclick(int paramInt1, int paramInt2, View paramView);
    }


}
